package com.smark.sk_audio.mediaplayer.db;


import android.database.sqlite.SQLiteDatabase;

import com.smark.sk_audio.app.AudioHelper;
import com.smark.sk_audio.mediaplayer.model.AudioBean;
import com.smark.sk_audio.mediaplayer.model.Favourite;


/**
 * Created by smark on 2020/1/9.
 * 邮箱：smarkwzp@163.com
 * 操作greenDao数据库帮助类
 */
public class GreenDaoHelper {

    private static final String DB_NAME = "music_db";

    private static DaoMaster.DevOpenHelper mHelper;
    private static SQLiteDatabase mDb;
    //管理数据库
    private static DaoMaster mDaoMaster;
    //管理各种实体Dao,不让业务层拿到session直接去操作数据库，统一由此类提供方法
    private static DaoSession mDaoSession;


    /**
     * 初始化
     */
    public static void initDatabase() {
        mHelper = new DaoMaster.DevOpenHelper(AudioHelper.getContext(), DB_NAME);
        mDb = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(mDb);
        mDaoSession = mDaoMaster.newSession();
    }


    /**
     * 添加收藏
     *
     * @param audioBean
     */
    public static void addFavourite(AudioBean audioBean) {
        FavouriteDao dao = mDaoSession.getFavouriteDao();
        Favourite favourite = new Favourite();
        favourite.setAudioId(audioBean.id);
        favourite.setAudioBean(audioBean);
        dao.insertOrReplace(favourite);

    }


    /**
     * 删除收藏
     * @param bean
     */
    public static void removeFavourite(AudioBean bean) {
        FavouriteDao dao = mDaoSession.getFavouriteDao();
        Favourite favourite = selectFavourite(bean);
        dao.delete(favourite);

    }

    /**
     * 查询一个收藏
     * @param bean
     * @return
     */
    public static Favourite selectFavourite(AudioBean bean){
        FavouriteDao dao = mDaoSession.getFavouriteDao();
        Favourite favourite = dao.queryBuilder()
                .where(FavouriteDao.Properties.AudioId.eq(bean.id))
                .unique();
        return favourite;
    }


}
